package leetcode.medium.limit500;

import leetcode.ListNode;

import java.util.Stack;

public class No445 {
    public static void main(String[] args) {
        ListNode l1 = ListNode.createByArray(new int[]{7, 2, 4, 3});
        ListNode l2 = ListNode.createByArray(new int[]{5, 6, 4});
        No445 no445 = new No445();
        ListNode listNode = no445.addTwoNumbers(l1, l2);
        ListNode.print(listNode);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode d = new ListNode(-1);
        Stack<Integer> stack1 = new Stack<>();
        while (l1 != null) {
            stack1.push(l1.val);
            l1 = l1.next;
        }

        Stack<Integer> stack2 = new Stack<>();
        while (l2 != null) {
            stack2.push(l2.val);
            l2 = l2.next;
        }
        Integer l1Val = stack1.pop();
        Integer l2Val = stack2.pop();
        int carry = 0;
        while (l1Val != null || l2Val != null || carry != 0) {
            int val = (l1Val == null ? 0 : l1Val) + (l2Val == null ? 0 : l2Val) + carry;
            carry = val / 10;
            val = val % 10;
            ListNode newNode = new ListNode(val);
            newNode.next = d.next;
            d.next = newNode;
            l1Val = stack1.isEmpty() ? null : stack1.pop();
            l2Val = stack2.isEmpty() ? null : stack2.pop();
        }
        return d.next;
    }
}
